package com.dreamtour.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dreamtour.entity.Administrators;
import com.dreamtour.mapper.AdministratorsMapper;
import com.dreamtour.service.IAdministratorsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xls
 * @since 2024-12-24
 */
@RestController
@RequestMapping("/administrators")
public class AdministratorsController {
    @Autowired
    private IAdministratorsService administratorsService;
    @RequestMapping("/getByPage")
    public IPage<Administrators> getByPage(Integer pageNum, Integer pageSize) {
        IPage<Administrators> page = administratorsService.page(new Page<>(pageNum, pageSize));
        return page;
    }

    @RequestMapping("/getByName")
    public List<Administrators> getByName(String adminId) {
        QueryWrapper<Administrators> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("adminId", adminId);
        List<Administrators> list = administratorsService.list(queryWrapper);
        return list;
    }

    @GetMapping("/filter")
    public ResponseEntity<Map<String, Object>> filterUsers(
            @RequestParam(required = false) String authorityLevel) {

        QueryWrapper<Administrators> queryWrapper = new QueryWrapper<>();

        // 添加验证状态筛选条件
        if (authorityLevel != null && !authorityLevel.isEmpty()) {
            queryWrapper.eq("authorityLevel", authorityLevel);
        }

        // 查询符合条件的旅行社
        List<Administrators> filteredUsers = administratorsService.list(queryWrapper);

        // 准备返回数据
        Map<String, Object> response = new HashMap<>();
        response.put("administrators", filteredUsers);

        return ResponseEntity.ok(response);
    }

    @RequestMapping("/update")
    public boolean update(@RequestBody Administrators administrators) {
        boolean b = administratorsService.updateById(administrators);
        return b;
    }

    @RequestMapping("/getAdministratorsCountByMonth")
    public ResponseEntity<List<Map<String, Object>>> getAdministratorsCountByMonth() {
        List<Map<String, Object>> monthlyCounts = administratorsService.countAdministratorsByMonth();

        // 直接返回原始的统计数据列表
        return ResponseEntity.ok(monthlyCounts);
    }
    @RequestMapping("/add")
    public boolean add(@RequestBody Administrators administrators) {
        boolean b = administratorsService.save(administrators);
        return b;
    }

    @Autowired
    private AdministratorsMapper administratorsMapper;

    @CrossOrigin(origins = "http://localhost:5173")  // 确保这里的 URL 是前端实际的地址
// 登录接口
    // 登录接口
    // 登录接口
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        String phone = loginRequest.getAdminPhone();  // 获取管理员手机号
        System.out.println("接收到的手机号：" + phone);  // 打印接收到的手机号

        // 查询管理员信息
        Administrators admin = administratorsMapper.selectByPhone(phone);
        System.out.println("查询到的管理员：" + admin);  // 打印查询到的管理员信息

        // 如果管理员不存在
        if (admin == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseMessage("管理员不存在"));
        }

        // 比较密码是否正确
        if (!admin.getAdminPwd().equals(loginRequest.getAdminPwd())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(new ResponseMessage("密码错误"));
        }

        // 更新登录时间
        LocalDateTime now = LocalDateTime.now();  // 获取当前时间
        admin.setLastLogtime(now);  // 设置管理员的登录时间

        // 保存管理员信息（更新登录时间）
        administratorsMapper.updateById(admin);

        // 登录成功，返回包含权限等级和 adminId 的响应
        String authorityLevel = admin.getAuthorityLevel();  // 获取管理员权限等级

        // 构造一个返回的响应体，包含登录消息、权限等级和 adminId
        Map<String, Object> response = new HashMap<>();
        response.put("message", "登录成功");
        response.put("authorityLevel", authorityLevel);  // 添加权限等级字段
        response.put("adminId", admin.getAdminId());    // 添加 adminId 字段

        return ResponseEntity.ok(response);  // 返回包含权限等级和 adminId 的响应
    }



    @CrossOrigin(origins = "http://localhost:5173")  // 确保这里的 URL 是前端实际的地址
    // 获取当前用户信息
    @GetMapping("/getUserInfo")
    public ResponseEntity<?> getUserInfo(@RequestParam("adminId") Integer adminId) {
        System.out.println("Received adminId: " + adminId);  // 调试日志
        Administrators admin = administratorsMapper.selectById(adminId);
        if (admin == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseMessage("用户不存在"));
        }
        System.out.println("Admin info: " + admin);  // 打印查询到的管理员信息

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("userData", new HashMap<String, Object>() {{
            put("adminPhone", admin.getAdminPhone());
            put("lastLogtime", admin.getLastLogtime());
            put("authorityLevel", admin.getAuthorityLevel());
        }});

        return ResponseEntity.ok(response);
    }




    // 修改手机号接口
    @PutMapping("/updatePhone")
    @CrossOrigin(origins = "http://localhost:5173")
    public ResponseEntity<?> updatePhone(@RequestBody UpdatePhoneRequest updatePhoneRequest) {
        Integer adminId = updatePhoneRequest.getAdminId();
        String newPhone = updatePhoneRequest.getNewPhone();

        // 校验手机号是否符合格式
        if (!isValidPhone(newPhone)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage("invalidPhone"));
        }

        // 直接根据 adminId 更新手机号
        Administrators admin = administratorsMapper.selectById(adminId);
        if (admin == null) {
            // 如果找不到管理员，说明 adminId 不合法
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage("adminNotFound"));
        }

        // 校验手机号是否已存在
        Administrators existingAdmin = administratorsMapper.selectByPhone(newPhone);
        if (existingAdmin != null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage("phoneExists"));
        }

        // 更新手机号
        admin.setAdminPhone(newPhone);
        administratorsMapper.updateById(admin);  // 更新数据库中的手机号

        return ResponseEntity.ok(new ResponseMessage("success"));  // 返回成功标识
    }




    // 判断手机号是否有效
    private boolean isValidPhone(String phone) {
        return phone != null && phone.matches("^1[3-9]\\d{9}$");  // 简单的手机号正则表达式
    }

    // 修改密码接口
    @CrossOrigin(origins = "http://localhost:5173")
    @PutMapping("/updatePassword")
    public ResponseEntity<?> updatePassword(@RequestBody UpdatePasswordRequest request) {
        String adminId = request.getAdminId();
        String newPassword = request.getNewPassword();

        // 校验 adminId 和新密码
        Administrators admin = administratorsMapper.selectById(adminId);
        if (admin == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage("adminNotFound"));
        }

        // 更新密码
        admin.setAdminPwd(newPassword);
        boolean success = administratorsService.updateById(admin);

        if (success) {
            return ResponseEntity.ok(new ResponseMessage("success"));
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ResponseMessage("error"));
        }
    }



    // 将 UpdatePasswordRequest 变成静态类，或者提取到外部类
    public static class UpdatePasswordRequest {
        private String adminId;
        private String newPassword;

        // 无参构造方法
        public UpdatePasswordRequest() {}

        public String getAdminId() {
            return adminId;
        }

        public void setAdminId(String adminId) {
            this.adminId = adminId;
        }

        public String getNewPassword() {
            return newPassword;
        }

        public void setNewPassword(String newPassword) {
            this.newPassword = newPassword;
        }
    }


    // 修改手机号请求数据模型
    public static class UpdatePhoneRequest {
        private Integer adminId;
        private String newPhone;

        // Getters and Setters
        public Integer getAdminId() {
            return adminId;
        }

        public void setAdminId(Integer adminId) {
            this.adminId = adminId;
        }

        public String getNewPhone() {
            return newPhone;
        }

        public void setNewPhone(String newPhone) {
            this.newPhone = newPhone;
        }
    }



    // 登录请求数据模型
    public static class LoginRequest {
        private String adminPhone;  // 修改为 adminPhone
        private String adminPwd;    // 修改为 adminPwd

        // Getters and Setters
        public String getAdminPhone() {
            return adminPhone;
        }

        public void setAdminPhone(String adminPhone) {
            this.adminPhone = adminPhone;
        }

        public String getAdminPwd() {
            return adminPwd;
        }

        public void setAdminPwd(String adminPwd) {
            this.adminPwd = adminPwd;
        }
    }

    // 登录响应消息模型
    public static class ResponseMessage {
        private String message;
        private String authorityLevel;  // 添加权限等级字段
        public ResponseMessage(String message) {
            this.message = message;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }
        public String getAuthorityLevel() {
            return authorityLevel;
        }

        public void setAuthorityLevel(String authorityLevel) {
            this.authorityLevel = authorityLevel;
        }
    }

    // 注册接口
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody Administrators administrator) {
        // 1. 校验手机号是否已存在
        Administrators existingAdmin = administratorsMapper.selectByPhone(administrator.getAdminPhone());
        if (existingAdmin != null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage("该手机号已被注册"));
        }

        // 2. 设置默认的权限等级为 4
        administrator.setAuthorityLevel("4");

        // 3. 设置默认的 state 为 0
        administrator.setState(0);

        // 3. 保存管理员数据到数据库
        administratorsMapper.insert(administrator);

        // 4. 返回成功响应
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage("注册成功"));
    }




}
